from django.shortcuts import render, redirect, HttpResponse
from utils.pay import AliPay
import json
import time


def ali():
    app_id = "2016082600311824"#测试用
    # app_id = "2017112400142095" #真实应用

    # POST
    # notify_url = "http://47.94.172.250:8804/page2/"
    notify_url = "http://39.108.221.252:8009/page2/"

    # GET
    return_url = "http://39.108.221.252:8009/page2/"

    merchant_private_key_path = "keys/pri"
    alipay_public_key_path = "keys/pub"

    alipay = AliPay(
        appid=app_id,
        app_notify_url=notify_url,
        return_url=return_url,
        app_private_key_path=merchant_private_key_path,
        alipay_public_key_path=alipay_public_key_path,  # 支付宝的公钥，加密信息传给支付宝时使用，不是你自己的公钥
        debug=True,  # 默认False,True的话是使用debug模式,调用沙箱的支付,网关为alipaydev,False是真正的支付
    )
    return alipay


def page1(request):
    if request.method == "GET":
        return render(request, 'page1.html')
    else:
        money = float(request.POST.get('money'))
        alipay = ali()
        # 生成支付的url
        query_params = alipay.direct_pay(
            subject="充气式韩红",  # 商品简单描述
            out_trade_no="x2" + str(time.time()),  # 商户订单号
            total_amount=money,  # 交易金额(单位: 元 保留俩位小数)
        )

        pay_url = "https://openapi.alipaydev.com/gateway.do?{}".format(query_params)
        # pay_url = "https://openapi.alipay.com/gateway.do?{}".format(query_params)
        print(pay_url)

        return redirect(pay_url)


def page2(request):
    alipay = ali()
    if request.method == "POST":
        # 检测是否支付成功
        # 去请求体中获取所有返回的数据：状态/订单号
        from urllib.parse import parse_qs

        # request.body                  => 字节类型
        # request.body.decode('utf-8')  => 字符串类型
        """
        {"k1":["v1"],"k2":["v1"]}
        k1=[v1]&k2=[v2]
        """
        body_str = request.body.decode('utf-8')
        post_data = parse_qs(body_str)
        # {k1:[v1,],k2:[v2,]}

        # {k1:v1}
        post_dict = {}
        for k, v in post_data.items():
            post_dict[k] = v[0]


        # print(post_dict)
        """
        post_dict {'gmt_create': '2017-11-24 17:27:07', 'charset': 'utf-8', 'gmt_payment': '2017-11-24 17:27:16', 'notify_time': '2017-11-24 17:27:18', 'subject': '充气式韩红', 'buyer_id': '2088102175132945', 'invoice_amount': '111.00', 'version': '1.0', 'notify_id': '4025ab6d369f1dfa2d0377a10c0396an96', 'fund_bill_list': '[{"amount":"111.00","fundChannel":"ALIPAYACCOUNT"}]', 'notify_type': 'trade_status_sync', 'out_trade_no': 'x21511515622.4174361', 'total_amount': '111.00', 'trade_status': 'TRADE_SUCCESS', 'trade_no': '2017112421001004940200320966', 'auth_app_id': '2016082600311824', 'receipt_amount': '111.00', 'point_amount': '0.00', 'app_id': '2016082600311824', 'buyer_pay_amount': '111.00', 'seller_id': '2088102173078946'}

        """
        sign = post_dict.pop('sign', None)

        status = alipay.verify(post_dict, sign)

        print('POST验证', status)

        if status:
            # print("post_dict",post_dict)
            print("trade_status",post_dict['trade_status'])
            print("trade_no",post_dict['trade_no'])
            return HttpResponse('success')
        else:
            print("POST验证未通过....")
    else:
        # QueryDict = {'k':[1],'k1':[11,22,3]}
        params = request.GET.dict()
        print("GET返回的dict:",params)
        sign = params.pop('sign', None)
        status = alipay.verify(params, sign)
        print('GET验证', status)
        return HttpResponse('支付成功')


def ali_callback(request,*args,**kwargs):
    print(args)
    print(kwargs)
    print("ali_callback")
    return HttpResponse("ok")

def ali_app_gateway(request,*args,**kwargs):
    print(args)
    print(kwargs)
    print("ali_app_gateway")
    return HttpResponse("ok")